package ynu.edu.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ConsumerService {

    @Autowired
    private RestTemplate restTemplate;

    private final String BASE_URL = "http://localhost:8080/api/resource/";

    // GET请求示例
    public void getMethod() {
        ResponseEntity<String> response = restTemplate.getForEntity(BASE_URL + "resourceId", String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("GET请求结果：" + response.getBody());
        } else {
            System.out.println("GET请求失败");
        }
    }

    // POST请求示例
    public void postMethod() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String requestBody = "{\"name\":\"Resource Name\",\"description\":\"Resource Description\"}";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(BASE_URL, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.CREATED) {
            System.out.println("POST请求结果：" + response.getBody());
        } else {
            System.out.println("POST请求失败");
        }
    }

    // PUT请求示例
    public void putMethod() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        String requestBody = "{\"name\":\"Updated Resource Name\",\"description\":\"Updated Resource Description\"}";
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

        restTemplate.put(BASE_URL + "resourceId", requestEntity);
        System.out.println("PUT请求成功");
    }

    // DELETE请求示例
    public void deleteMethod() {
        restTemplate.delete(BASE_URL + "resourceId");
        System.out.println("DELETE请求成功");
    }
}